package rpc

import (
	"bestgo/pkg/codec"
	"io"
	"net/rpc"
	"sync"
)

// ================ 服务端代码增强 ================
// 服务端专用编解码器（增加多路复用支持）
type serverCodec struct {
	rpc.ClientCodec
	reqLock sync.Mutex
}

func NewServerCodec(conn io.ReadWriteCloser, level int) rpc.ServerCodec {
	return &serverCodec{
		ClientCodec: codec.NewCompressedGobCodec(conn, level),
	}
}

func (s *serverCodec) ReadRequestHeader(r *rpc.Request) error {
	s.reqLock.Lock()
	defer s.reqLock.Unlock()
	return s.ClientCodec.ReadResponseHeader(&rpc.Response{})
}

func (s *serverCodec) ReadRequestBody(body interface{}) error {
	return s.ClientCodec.ReadResponseBody(body)
}

func (s *serverCodec) WriteResponse(r *rpc.Response, body interface{}) error {
	// 复用请求写入逻辑
	return s.ClientCodec.WriteRequest(
		&rpc.Request{ServiceMethod: r.ServiceMethod},
		struct {
			Header *rpc.Response
			Body   interface{}
		}{r, body},
	)
}

func (s *serverCodec) Close() error {
	return s.ClientCodec.Close()
}
